package walker

import (
	"fmt"
	"io/fs"
	"log"
	"os"
	"path"
)

func listDir2(directorys ...string) (dirs []fs.DirEntry, files []fs.DirEntry) {
	dir := path.Join(directorys...)
	lists, err := os.ReadDir(dir)
	if err != nil {
		log.Fatalf("list dir err:path=%s, err=%v", dir, err)
	}

	dirs = make([]fs.DirEntry, 0, 10)
	files = make([]fs.DirEntry, 0, 10)

	for _, f := range lists { // sorted by name
		// fmt.Printf("f.Name(): %v\n", f.Name())
		if f.IsDir() {
			dirs = append(dirs, f)
			// fmt.Printf("is dir f.Name(): %v\n", f.Name())
		} else if f.Type().IsRegular() {
			files = append(files, f)
			// fmt.Printf("is regular f.Name(): %v\n", f.Name())
		} else if f.Type()&os.ModeSymlink != 0 {
			if finfo, err := os.Stat(path.Join(dir, f.Name())); err == nil && finfo.IsDir() {
				fmt.Printf("[i] is ModeSymlink && target is Dir f.Name(): %v\n", f.Name())
				// 不处理 软连接的文件!
				dirs = append(dirs, f)
			}
		}
	}
	return
}

func listDir(directorys ...string) (dirs_files []fs.DirEntry) {
	dir := path.Join(directorys...)
	lists, err := os.ReadDir(dir)
	if err != nil {
		log.Fatalf("list dir err:path=%s, err=%v", dir, err)
	}

	dirs_files = make([]fs.DirEntry, 0, 10)

	// 软连接 包含在里面吗? 不, 需要重新处理.
	for _, f := range lists { // sorted by name
		if f.IsDir() || f.Type().IsRegular() {
			dirs_files = append(dirs_files, f)
		}
	}

	// } else if f.Type()&os.ModeSymlink != 0 {
	// 	if finfo, err := os.Stat(path.Join(dir, f.Name())); err == nil && finfo.IsDir() {
	// 		fmt.Printf("[i] is ModeSymlink && target is Dir f.Name(): %v\n", f.Name())
	// 		// 不处理 软连接的文件!
	// 		dirs = append(dirs, f)
	// 	}
	// }
	return
}
